<template>
    <el-container>
        <el-main>
            <el-form ref="purchaseForm" :model="form" :rules="rules" label-width="90px">
                <!--<div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">-->
                    <!--<span style="font-size: 18px;color:#409EFF;margin: 10px 0;">退货单信息</span>-->
                <!--</div>-->
                <div style="display: flex">
                    <el-form-item label="供应商名" prop="supplierId">
                        <el-select style="width: 200px" v-model="supplierName" value-key="id" :filter-method="remoteMethod" filterable placeholder="请选择供应商" @change="selectSupplier">
                            <el-option v-for="item in suppliers" :key="item.id" :label="item.name" style="width: 600px" :value="item">
                                <div style="display: flex">
                                    <span style="float: left;width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
                                    <span style="width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.phone }}</span>
                                    <div style="width: 200px;">
                                        <span style="color: #8492a6; font-size: 8px;">{{item.areaName}}{{item.address}}</span>
                                    </div>
                                </div>
                            </el-option>
                            <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                                <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                                <div class="elOption" @click="toSearchSupplier">搜索供应商</div>
                                <div class="elOption1" @click="toAddSupplier">新增供应商</div>
                            </div>
                            <div style="height: 30px"></div>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="退货日期" prop="orderDate">
                        <el-date-picker style="width: 200px" v-model="form.orderDate" type="date" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <!-- <el-form-item label="所属部门" prop="officeId">
              <el-input v-model="officeName" style="width: 330px" suffix-icon="el-icon-arrow-down"
                @focus="dialogShow" />
            </el-form-item> -->
                    <el-form-item label="采购人员">
                        <el-select style="width: 200px" v-model="operatorName" value-key="id" filterable placeholder="请选择" @change="selectSysEmployee">
                            <el-option v-for="item in sysEmployeeList" :key="item.id" :label="item.name" :value="item">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div style="display: flex">
                    <el-form-item label="入库仓库" style="width: 290px" prop="shopId">
                        <el-select style="width: 200px" value-key="id" v-model="form.shopName" filterable placeholder="请选择" @change="selectShop">
                            <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="开票类型">
                        <el-select style="width: 200px" v-model="taxType" placeholder="请选择">
                            <el-option label="不开票" value="0"></el-option>
                            <el-option label="增票" value="1"></el-option>
                            <el-option label="普票" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="收货姓名" prop="consignee">
                        <el-input v-model="form.consignee" style="width: 200px" />
                    </el-form-item>
                </div>
                <div style="display: flex">
                    <el-form-item label="详细地址" prop="address">
                        <el-input v-model="form.address" style="width: 490px" />
                    </el-form-item>

                    <el-form-item label="收货电话" prop="phone">
                        <el-input v-model="form.phone" style="width: 200px" />
                    </el-form-item>
                </div>
                <div>
                    <el-form-item label="退货留言">
                        <el-input style="width: 780px" placeholder="请输入留言" v-model="form.memo" />
                    </el-form-item>
                    <!-- <div style="display: flex;margin-right: 20px;align-items: center">
                <span style="font-size: 16px;color: #606266;width: 80px;">留言备注：</span>
                <div style="width: 320px">

                </div>
              </div> -->
                </div>

              <div class="product_header_name">
                <span style="font-size: 18px;color:#409EFF;margin: 5px 10px;">退货明细</span>
                <div style="display: flex;padding-top: 5px;padding-bottom: 5px">
                  <el-input v-model="query.sn" placeholder="请输入货号" @change="queryClick"></el-input>
                  <!--            <el-button style="margin-left: 20px;margin-right: 10px" type="primary" icon="el-icon-plus"-->
                  <!--                       @click="moreProductClick">批量录入-->
                  <!--            </el-button>-->
                </div>
              </div>
                <!--商品规格-->
                <el-table :data="productList" border show-summary stripe style="width: 100%">
                    <el-table-column label="排序" type="index" width="50">
                    </el-table-column>
                    <el-table-column label="商品名" width="200">
                        <template slot-scope="{row}">
                            <div style="position: relative">
                                <i class="el-icon-arrow-down" style="position: absolute;bottom: 11px;color: #CCCC;right: 8px;z-index: 99;"></i>
                                <el-select v-model="row.name" filterable placeholder="请选择" remote :remote-method="productMethod" @change="selectClick" @focus="tableClick(row)">
                                    <el-option v-for="(item,index) in listForm" :key="index" style="width:650px" :label="item.name" :value="index">
                                        <div style="display: flex">
                                            <span style="width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.sn }}</span>
                                            <span style="float: left;width: 160px;overflow: hidden;text-overflow: ellipsis;margin-left: 10px">{{ item.name }}</span>
                                            <div style="width: 200px;">
                                                <span style="color: #8492a6; font-size: 8px;">{{item.spec1}}</span>
                                            </div>
                                        </div>
                                    </el-option>
                                    <div style="display: flex;width: 100%;position: absolute;bottom: 0">

                                        <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                                        <div class="elOption" @click="toAddProduct">搜索商品</div>
                                        <div class="elOption1" @click="toSearchProduct">新增商品</div>
                                    </div>
                                    <div style="height: 30px"></div>
                                </el-select>
                            </div>

                        </template>
                    </el-table-column>
                    <el-table-column label="规格" width="100" align="center">
                        <template slot-scope="{row}">
                            <span>{{row.spec}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="货号/条码">
                        <template slot-scope="{row}">
                            <span>{{row.sn}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="单位" width="100" align="center">
                        <template slot-scope="{row}">
                            <span>{{row.unit}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" prop="quantity" width="100">
                        <template slot-scope="{row}">
                            <el-input @change="refreshClick" v-model="row.quantity" />
                        </template>
                    </el-table-column>
                    <el-table-column label="单价" width="100">
                        <template slot-scope="{row}">
                            <el-input @change="refreshClick" v-model="row.price" />
                        </template>
                    </el-table-column>
                    <el-table-column label="金额" width="100" align="right" prop="subTotal">
                    </el-table-column>
                    <el-table-column label="优惠" width="100" align="right">
                        <template slot-scope="{row}">
                            <el-input @change="refreshClick" v-model="row.discount" />
                        </template>
                    </el-table-column>
                    <el-table-column label="实付" width="100" align="right" prop="amountPaid">
                    </el-table-column>
                    <el-table-column align="center" width="100" label="操作">
                        <template slot-scope="{row}">
                            <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                                <a @click="delProduct(row)">
                                    <i style="color: #F56C6C" class="el-icon-delete"></i>
                                </a>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="background-color: #EBEEF5;width: 100%;border-left: 1px solid #DCDFE6;border-right: 1px solid #DCDFE6;border-bottom: 1px solid #DCDFE6;display: flex;justify-content: space-between;padding: 10px;">
                    <div style="display: flex;flex-direction: column">
                        <div style="display:flex;align-items: center;justify-content: space-between;margin-bottom: 10px">
                            <div style="display: flex;margin-right: 20px;align-items: center">
                                <span style="font-size: 16px;color: #606266;width: 80px;">运费：</span>
                                <div style="width: 100px">
                                    <el-input v-model="form.freight" @input="toCalculateClick" />
                                </div>
                            </div>
                        </div>
                        <!-- <div>
                <el-form-item label="留言备注" style="width: 560px;margin-top:30px">
                  <el-input v-model="form.memo" />
                </el-form-item>
              </div> -->
                    </div>
                    <div>
                        <div>
                            <span style="font-size: 16px;color: #F56C6C">应退：{{form.amountPayable.toFixed(2)}}</span>
                        </div>
                    </div>
                </div>
                <div style="display: flex;justify-content: flex-end">
                    <!-- <el-button type="primary" style="margin-top: 20px" v-permission="['purchasein.in']" :loading="clicked" @click="saveInstockClick('purchaseForm')">保存并入库</el-button> -->
                    <el-button type="success" style="margin-top: 20px" :loading="clicked" @click="saveConfirmClick('purchaseForm')">保存并确认</el-button>
                    <el-button style="margin-top: 20px" :loading="clicked" @click="saveClick('purchaseForm')">保存至草稿
                    </el-button>
                </div>
            </el-form>
            <el-dialog title="新增商品" :visible.sync="procuctVisible" width="950px" v-el-drag-dialog :before-close="productClose">
                <div style="height: 65vh;overflow: auto;position: relative;">
                    <productAdd :type="productType" @saveProduct="saveProduct"></productAdd>
                </div>
            </el-dialog>
            <el-dialog title="商品选择" :visible.sync="orderVisible" width="950px" v-el-drag-dialog :before-close="orderClose">
                <div style="position: relative;">
                    <productTable ref="productList" @doubleClick="doubleClick" @orderClose="orderClose" @addClick="addClick">
                    </productTable>
                </div>
            </el-dialog>
            <el-dialog title="查找供应商" :visible.sync="supplierVisible" width="950px" v-el-drag-dialog append-to-body :before-close="supplierClose">
                <div style="position: relative;height: 63vh;overflow: auto">
                    <supplierTable :key="times" @doubleSupplier="doubleSupplier"></supplierTable>
                </div>
            </el-dialog>
            <el-dialog title="选择商品" :visible.sync="queryType" width="950px" v-el-drag-dialog append-to-body :before-close="queryClose">
                <div style="position: relative;height: 60vh;overflow: auto">
                    <productRadio :findByList="findByList" @findByClick="findByClick"></productRadio>
                </div>
            </el-dialog>
            <el-dialog title="添加供应商" :visible.sync="suppVisible" width="950px" v-el-drag-dialog :before-close="suppClose">
                <div style="height: 70vh;overflow: auto;position: relative;">
                    <suppAdd :isDialog="true" @confirm="suppAddConfirm"></suppAdd>
                </div>
            </el-dialog>

            <office-dialog ref="officeDialog" @confirm="dialogConfirm" />
        </el-main>
    </el-container>
</template>

  <script>
import permission from "@/directive/permission/index.js"; // 权限判断指令
import { mapGetters } from "vuex";
import { EventBus } from "@/api/eventBus";
import { calculate } from "@/api/order";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import productAdd from "@/views/product/add";
import suppAdd from "../supplier/add.vue";
import productTable from "../../components/ProductList/productList";
import { list as supplierList } from "../../api/supplier";
import { list as sysEmployeeList } from "@/api/sysEmployee";
import supplierTable from "../../components/SupplierTable/supplierList";
import productRadio from "./components/productRadio";
import OfficeDialog from "@/components/OfficeDialog";
import Distpicker from "@/components/Distpicker/Distpicker";
import utils from "../../utils/utils";
import { findBySn } from "../../api/product";
import { save, saveAndConfirm, saveAndInStock } from "../../api/purchase";
import { list as productList } from "@/api/product";
import { list as shopList } from "@/api/shop";

export default {
    directives: {
        elDragDialog,
        permission,
    },
    name: "purchasereturn-add",
    data() {
        return {
            selecttimes: null,
            supplierVisible: false,
            clicked: false, // 按钮防双击
            supplier: {},
            times: "",
            suppVisible: false,
            shopList: [],
            supplierName: "",
            form: {
                offsetAmount: 0,
                supplierId: "",
                orderDate: new Date(),
                operatorId: "",
                // property: 0,
                officeId: "",
                areaId: null,
                areaName: "",
                shopId: "",
                shopName: "",
                address: "",
                memo: "",
                consignee: "",
                phone: "",
                freight: 0,
                amountPayable: 0,
                amountPaid: 0,
                subPrice: 0,
                subQuantity: 0,
            },
            productList: [],
            query: {
                sn: "",
            },
            keyword: {
                sn: "",
            },
            suppliers: [],
            taxType: "0",
            listForm: [],
            tableIndex: "",
            procuctVisible: false,
            orderVisible: false,
            productType: "order",
            chooseOrderName: "",
            sysEmployeeList: [],
            operatorName: "",
            officeName: "",
            rules: {
                supplierId: [
                    {
                        required: true,
                        message: "供应商不能为空",
                        trigger: "blur",
                    },
                ],
                orderDate: [
                    {
                        required: true,
                        message: "请选择退货日期",
                        trigger: "blur",
                    },
                ],
                shopId: [
                    {
                        required: true,
                        message: "请选择入库仓库",
                        trigger: "blur",
                    },
                ],
            },
            queryType: false,
            findByList: [],
        };
    },
    computed: {
        ...mapGetters(["employee"]),
    },
    created() {
        this.times = new Date().getSeconds();
        if (this.employee != null) {
            this.form.operatorId = this.employee.id;
            this.form.officeId = this.employee.officeId;
            this.officeName = this.employee.officeName;
            this.operatorName = this.employee.name;
            this.form.shopId = this.employee.shopId;
            this.form.shopName = this.employee.shopName;
        }
        console.log(this.form.operatorId);
        this.loadlist("");
        this.loadShop();
        this.loadSupplier("");
        this.loadSysEmployee();
    },
    computed: {
        ...mapGetters(["employee"]),
    },
    methods: {
        //  仓库
        loadShop() {
            var _this = this;
            const params = new URLSearchParams();
            params.append("pageSize", 100);
            shopList(params)
                .then((response) => {
                    _this.shopList = response.data.data;
                })
                .catch((error) => {
                    console.log("error!!");
                });
        },
        suppClose() {
            this.suppVisible = false;
        },
        doubleSupplier(data) {
            this.form.supplierId = data.id;
            this.supplierName = data.name;
            this.supplierVisible = false;
        },
        toAddProduct() {
            this.orderVisible = true;
        },
        toSearchProduct() {
            this.procuctVisible = true;
        },
        toSearchSupplier() {
            this.times = new Date().getSeconds();
            this.supplierVisible = true;
        },
        toAddSupplier() {
            this.memberVisible = true;
            this.suppVisible = true;
        },
        suppAddConfirm(val) {
            this.suppliers.push(val);
            this.form.supplierId = val.id;
            this.suppVisible = false;
        },
        supplierClose() {
            this.supplierVisible = false;
        },
        productMethod(query) {
            this.loadlist(query);
        },
        loadSupplier(query) {
            let params = new URLSearchParams();
            params.append("name", query);
            supplierList(params).then((res) => {
                this.suppliers = res.data.data;
            });
        },
        //获取当前点击商品表行
        tableClick(data) {
            this.tableIndex = this.productList.indexOf(data);
            this.chooseOrderName = this.productList[this.tableIndex].name;
        },
        //新增商品
        addProduct() {
            var _this = this;
            if (_this.productList.length == 0) {
                _this.productList.push({
                    productId: "",
                    name: "",
                    sn: "",
                    price: "",
                    orders: "",
                    quantity: "",
                    subTotal: "",
                    amountPaid: 0,
                    spec: "",
                    discount: 0,
                    cost: 0,
                    unit: "",
                });
            } else {
                if (
                    _this.productList[_this.productList.length - 1].productId !=
                    ""
                ) {
                    _this.productList.push({
                        productId: "",
                        name: "",
                        sn: "",
                        price: "",
                        orders: "",
                        quantity: "",
                        subTotal: "",
                        amountPaid: 0,
                        spec: "",
                        discount: 0,
                        cost: 0,
                        unit: "",
                    });
                }
            }
        },
        selectSupplier(val) {
            if (val == "#") {
                this.form.supplierId = "";
                this.suppVisible = true;
            }
            if (this.supplierName != val.id) {
                this.productList = [];
                this.supplierName = val.name;
                this.form.supplierId = val.id;
            }
            this.loadSupplier("");
            this.addProduct();
        },
        remoteMethod(query) {
            this.loadSupplier(query);
        },
        //刷新商品合计
        refreshClick() {
            this.toCalculateClick();
            this.procuctFilter();
        },
        //商品表下拉选择
        selectClick(index) {
            var _this = this;
            if (index == "#") {
                _this.procuctVisible = true;
            } else if (index == "/") {
                this.orderVisible = true;
            } else {
                var goodsDetails = {
                    productId: _this.listForm[index].id,
                    name: _this.listForm[index].name,
                    sn: _this.listForm[index].sn,
                    cost: _this.listForm[index].cost,
                    price: _this.listForm[index].price,
                    orders: _this.listForm[index].orders,
                    subTotal: _this.listForm[index].price,
                    unit: _this.listForm[index].unit,
                    spec:
                        _this.listForm[index].spec1 +
                        _this.listForm[index].spec2,
                    amountPaid: 0,
                    discount: 0,
                    quantity: 1,
                };
                // debugger
                _this.productList[_this.tableIndex] = goodsDetails;
            }
            this.procuctFilter();
            this.addProduct();
        },
        //新增商品弹窗
        productClose() {
            this.procuctVisible = false;
            this.productList[this.tableIndex].name = this.chooseOrderName;
        },
        queryClose() {
            this.queryType = false;
        },
        memberClick(data) {
            var _this = this;
            _this.memberName = data.name;
            _this.form.memberId = data.id;
            _this.memberVisible = false;
        },
        memberClose() {
            this.memberVisible = false;
            this.memberName = "";
        },
        saveInstockClick(form) {
            const _this = this;
            this.$refs[form].validate((valid) => {
                console.log(valid);
                if (valid) {
                    // 校验表单
                    _this.clicked = true;
                    let itemList = [];
                    //            _this.productList=_this.productList.splice(_this.productList.length-1,1)
                    _this.productList.forEach(function (item) {
                        // debugger
                        if (item.productId != "") {
                            _this.form.subQuantity += Number(item.quantity);
                            _this.form.subPrice += Number(item.subTotal);
                            if (item.productId != "") {
                                var goodsDetails = {
                                    subTotal: item.subTotal,
                                    discount: Number(item.discount),
                                    productId: item.productId,
                                    name: item.name,
                                    sn: item.sn,
                                    price: item.price,
                                    quantity: item.quantity,
                                    spec: item.spec,
                                    cost: item.cost,
                                    unit: item.unit,
                                };
                                itemList.push(goodsDetails);
                            }
                        }
                    });
                    let formData = {
                        offsetAmount: Number(_this.form.offsetAmount),
                        supplierId: _this.form.supplierId,
                        orderDate: _this.form.orderDate,
                        shopId: _this.form.shopId,
                        operatorId: _this.form.operatorId,
                        officeId: _this.form.officeId,
                        areaName: _this.form.areaName,
                        address: _this.form.address,
                        areaId: _this.form.areaId,
                        memo: _this.form.memo,
                        phone: _this.form.phone,
                        consignee: _this.form.consignee,
                        freight: Number(_this.form.freight),
                        amountPayable: _this.form.amountPayable.toFixed(2),
                        amountPaid: Number(_this.form.amountPaid),
                        subPrice: _this.form.subPrice,
                        subQuantity: _this.form.subQuantity,
                        itemList: itemList,
                        type: 1,
                    };
                    saveAndInStock(formData)
                        .then((response) => {
                            _this.clicked = false;
                            EventBus.$emit("purchasereturn-add", response.data);
                            _this.$store
                                .dispatch("tagsView/delView", _this.$route)
                                .then(({ visitedViews }) => {
                                    _this.$router.push({
                                        path: "/purchasereturn/list",
                                    });
                                }); // 关闭当前tab回到列表
                        })
                        .catch((error) => {
                            _this.clicked = false;
                        });
                } else {
                    return false;
                }
            });
        },
        saveConfirmClick(form) {
            const _this = this;
            this.$refs[form].validate((valid) => {
                console.log(valid);
                if (valid) {
                    // 校验表单
                    _this.clicked = true;
                    let itemList = [];
                    _this.productList.forEach(function (item) {
                        _this.form.subQuantity += Number(item.quantity);
                        _this.form.subPrice += Number(item.subTotal);
                        if (item.productId != "") {
                            var goodsDetails = {
                                subTotal: item.subTotal,
                                discount: Number(item.discount),
                                productId: item.productId,
                                name: item.name,
                                sn: item.sn,
                                price: item.price,
                                quantity: item.quantity,
                                spec: item.spec,
                                cost: item.cost,
                                unit: item.unit,
                            };
                            itemList.push(goodsDetails);
                        }
                    });
                    let formData = {
                        offsetAmount: Number(_this.form.offsetAmount),
                        supplierId: _this.form.supplierId,
                        orderDate: _this.form.orderDate,
                        operatorId: _this.form.operatorId,
                        officeId: _this.form.officeId,
                        shopId: _this.form.shopId,
                        shopName: _this.form.shopName,
                        areaName: _this.form.areaName,
                        address: _this.form.address,
                        areaId: _this.form.areaId,
                        memo: _this.form.memo,
                        phone: _this.form.phone,
                        consignee: _this.form.consignee,
                        freight: Number(_this.form.freight),
                        amountPayable: _this.form.amountPayable.toFixed(2),
                        amountPaid: Number(_this.form.amountPaid),
                        subPrice: _this.form.subPrice,
                        subQuantity: _this.form.subQuantity,
                        itemList: itemList,
                        type: 1,
                    };
                    saveAndConfirm(formData)
                        .then((response) => {
                            _this.clicked = false;
                            EventBus.$emit("purchasereturn-add", response.data);
                            _this.$store
                                .dispatch("tagsView/delView", _this.$route)
                                .then(({ visitedViews }) => {
                                    _this.$router.push({
                                        path: "/purchasereturn/list",
                                    });
                                }); // 关闭当前tab回到列表
                        })
                        .catch((error) => {
                            _this.clicked = false;
                        });
                } else {
                    return false;
                }
            });
        },
        saveClick(form) {
            const _this = this;
            this.$refs[form].validate((valid) => {
                console.log(valid);
                if (valid) {
                    // 校验表单
                    _this.clicked = true;
                    let itemList = [];
                    _this.productList.forEach(function (item) {
                        _this.form.subQuantity += Number(item.quantity);
                        _this.form.subPrice += Number(item.subTotal);
                        if (item.productId != "") {
                            var goodsDetails = {
                                subTotal: item.subTotal,
                                discount: Number(item.discount),
                                productId: item.productId,
                                name: item.name,
                                sn: item.sn,
                                price: item.price,
                                quantity: item.quantity,
                                spec: item.spec,
                                cost: item.cost,
                                unit: item.unit,
                            };
                            itemList.push(goodsDetails);
                        }
                    });
                    let formData = {
                        offsetAmount: Number(_this.form.offsetAmount),
                        supplierId: _this.form.supplierId,
                        orderDate: _this.form.orderDate,
                        operatorId: _this.form.operatorId,
                        shopId: _this.form.shopId,
                        shopName: _this.form.shopName,
                        officeId: _this.form.officeId,
                        areaName: _this.form.areaName,
                        address: _this.form.address,
                        areaId: _this.form.areaId,
                        memo: _this.form.memo,
                        phone: _this.form.phone,
                        consignee: _this.form.consignee,
                        freight: Number(_this.form.freight),
                        amountPayable: _this.form.amountPayable.toFixed(2),
                        amountPaid: Number(_this.form.amountPaid),
                        subPrice: _this.form.subPrice,
                        subQuantity: _this.form.subQuantity,
                        itemList: itemList,
                        type: 1,
                    };
                    save(formData)
                        .then((response) => {
                            _this.clicked = false;
                            EventBus.$emit("purchasereturn-add", response.data);
                            _this.$store
                                .dispatch("tagsView/delView", _this.$route)
                                .then(({ visitedViews }) => {
                                    _this.$router.push({
                                        path: "/purchasereturn/list",
                                    });
                                }); // 关闭当前tab回到列表
                        })
                        .catch((error) => {
                            _this.clicked = false;
                        });
                } else {
                    return false;
                }
            });
        },

        queryClick() {
            var _this = this;
            let params = new URLSearchParams();
            params.append("sn", _this.query.sn);
            findBySn(params)
                .then((response) => {
                    console.log(response);
                    if (response.data.products.length == 1) {
                        var goodsDetails = {
                            productId: response.data.products[0].id,
                            name: response.data.products[0].name,
                            sn: response.data.products[0].sn,
                            cost: response.data.products[0].cost,
                            price: response.data.products[0].price,
                            orders: response.data.products[0].orders,
                            subTotal: response.data.products[0].price,
                            spec:
                                response.data.products[0].spec1 +
                                response.data.products[0].spec2,
                            amountPaid: 0,
                            discount: 0,
                            quantity: 1,
                            unit: response.data.products[0].unit,
                        };
                        _this.productList.push(goodsDetails);
                        _this.procuctFilter();
                    } else if (response.data.products.length > 1) {
                        _this.findByList = response.data.products;
                        _this.queryType = true;
                    }
                    _this.addProduct();
                })
                .catch((error) => {
                    console.log("error!!");
                });
        },
        //商品过滤
        procuctFilter() {
            let newfood = [];
            var temp = {};
            for (var i in this.productList) {
                if (this.productList[i].productId != "") {
                    var key = this.productList[i].productId;
                    if (temp[key]) {
                        temp[key].productId = temp[key].productId;
                        if (temp[key].quantity) {
                            temp[key].quantity =
                                temp[key].quantity +
                                this.productList[i].quantity;
                            temp[key].subTotal =
                                Number(this.productList[i].price) *
                                parseInt(temp[key].quantity);
                        } else {
                            temp[key].quantity = 1;
                            temp[key].subTotal = Number(
                                this.productList[i].price
                            );
                        }
                        if (this.productList[i].discount) {
                            temp[key].amountPaid =
                                temp[key].subTotal -
                                Number(this.productList[i].discount);
                        } else {
                            temp[key].amountPaid = temp[key].subTotal - 0;
                        }
                    } else {
                        temp[key] = {};
                        temp[key].productId = this.productList[i].productId;
                        if (this.productList[i].quantity) {
                            temp[key].quantity = this.productList[i].quantity;
                            temp[key].subTotal =
                                Number(this.productList[i].price) *
                                parseInt(temp[key].quantity);
                        } else {
                            temp[key].quantity = 1;
                            temp[key].subTotal = Number(
                                this.productList[i].price
                            );
                        }
                        if (this.productList[i].discount) {
                            temp[key].amountPaid =
                                temp[key].subTotal -
                                Number(this.productList[i].discount);
                        } else {
                            temp[key].amountPaid = temp[key].subTotal - 0;
                        }
                    }
                    temp[key].name = this.productList[i].name;
                    temp[key].sn = this.productList[i].sn;
                    temp[key].price = this.productList[i].price;
                    temp[key].cost = this.productList[i].cost;
                    temp[key].orders = this.productList[i].orders;
                    temp[key].discount = this.productList[i].discount;
                    temp[key].spec = this.productList[i].spec;
                    temp[key].unit = this.productList[i].unit;
                }
            }
            for (var k in temp) {
                newfood.push(temp[k]);
            }
            this.productList = newfood;
            console.log(this.productList);
            this.toCalculateClick();
        },
        receiverClose() {
            this.receiverType = false;
        },
        //删除商品列表
        delProduct(row) {
            var index = this.productList.indexOf(row);
            if (index !== -1) {
                this.productList.splice(index, 1);
            }
            this.addProduct();
        },
        dialogShow() {
            console.log("点击了");
            this.$refs.officeDialog.show();
        },
        selectSysEmployee(data) {
            this.form.operatorId = data.id;
        },

        dialogConfirm(val) {
            this.form.officeId = val.id;
            this.officeName = val.name;
            this.$refs["purchaseForm"].clearValidate();
        },
        findByClick(data) {
            var _this = this;
            console.log(data);
            data.forEach(function (item) {
                _this.productList.push(item);
            });
            this.queryType = false;
            this.procuctFilter();
        },
        saveProduct(data) {
            this.listForm.splice(0, 0, data);
            this.productList[this.tableIndex] = data;
            this.procuctVisible = false;
        },
        selectMember(data) {
            console.log(data);
            var _this = this;
            if (data == "#") {
                _this.memberVisible = true;
            } else {
                _this.form.memberId = data.id;
                if (!utils.isNull(data.areaId)) {
                    _this.form.address = data.address;
                    _this.form.areaName = data.areaName;
                    _this.form.areaId = data.areaId;
                    _this.district = utils.decodeArea(
                        JSON.stringify(data.areaId)
                    );
                } else {
                    _this.form.address = "";
                    _this.form.areaName = "广州市,海珠区";
                    _this.form.areaId = "440000";
                    _this.district = utils.decodeArea("440000");
                }
            }
        },

        loadSysEmployee() {
            var _this = this;
            let params = new URLSearchParams();
            params.append("pageSize", 100);
            sysEmployeeList(params)
                .then((response) => {
                    _this.sysEmployeeList = response.data.data;
                })
                .catch((error) => {
                    console.log("error!!");
                });
        },
        addClick(data) {
            var _this = this;
            data.forEach((item) => {
                var goodsDetails = {
                    productId: item.id,
                    name: item.name,
                    sn: item.sn,
                    price: item.price,
                    cost: item.cost,
                    spec: item.spec1 + item.spec2,
                    unit: item.unit,
                };
                _this.productList.push(goodsDetails);
            });
            this.procuctFilter();
            this.addProduct();
        },
        //商品总数据
        loadlist(query) {
            var _this = this;
            let params = new URLSearchParams();
            params.append("keyword", query);
            params.append("sn", _this.keyword.sn);
            productList(params)
                .then((response) => {
                    _this.listForm = response.data.data;
                })
                .catch((error) => {
                    console.log("error!!");
                });
        },
        doubleClick(val) {
            var goodsDetails = {
                productId: val.id,
                name: val.name,
                sn: val.sn,
                price: val.price,
                orders: val.orders,
                subTotal: val.price,
                cost: val.cost,
                amountPaid: 0,
                discount: 0,
                quantity: 1,
                spec: val.spec1 + val.spec2,
                unit: val.unit,
            };
            this.productList.push(goodsDetails);
            this.procuctFilter();
            this.addProduct();
        },
        orderClose() {
            this.orderVisible = false;
            if (this.productList.length > 0 && this.chooseOrderName != "") {
                this.productList[this.tableIndex].name = this.chooseOrderName;
            }
        },
        toCalculateClick() {
            var _this = this;
            _this.form.amountPayable = 0;
            this.productList.forEach((item) => {
                _this.form.amountPayable += item.amountPaid;
            });
            if (this.form.freight != "") {
                _this.form.amountPayable += Number(this.form.freight);
            }
            if (this.form.offsetAmount != "") {
                _this.form.amountPayable -= Number(this.form.offsetAmount);
            }
        },
        selectShop(data) {
            console.log(data);
            (this.form.shopId = data.id), (this.form.shopName = data.name);
        },
    },
    components: {
        productAdd,
        productTable,
        Distpicker,
        OfficeDialog,
        productRadio,
        suppAdd,
        supplierTable,
    },
};
</script>
  <style scoped>
/deep/ .el-dialog__header {
    border-bottom: 1px solid #cccccc;
}

.elOption1 {
    background-color: #409eff;
    color: white;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;

    width: 25%;
    height: 40px;
}

.elOption {
    background-color: #909399;
    color: white;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;

    width: 25%;
    height: 40px;
}

.product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 20px;
    border-left: 5px #409eff solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
}
</style>
